package enterprisePerson

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetEnterprisCustomereListApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetEnterprisCustomereListApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetEnterprisCustomereListApiLogic {
	hostname, _ := os.Hostname()
	return &GetEnterprisCustomereListApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetEnterprisCustomereListApiLogic) GetEnterprisCustomereListApi(req *types.EnterpriseListReq) (resp []types.EnterpriseListResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	roleIdList := make([]int64, 0)
	if req.RoleCode != "" {
		roleEntity, err := service.RoleService.GetByCodeApi(l.ctx, accountInfo.EnterpriseId, req.RoleCode)
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			roleIdList = append(roleIdList, roleEntity.ID)
		}
	}
	personEntities, err := service.EnterprisePersonService.GetRoleIdApi(l.ctx, accountInfo.EnterpriseId, roleIdList)
	if err != nil || len(personEntities) == 0 {
		return make([]types.EnterpriseListResp, 0), nil
	}
	var result = make([]types.EnterpriseListResp, 0)
	for _, item := range personEntities {
		if item.Status == 1 {
			continue
		}
		result = append(result, types.EnterpriseListResp{
			ID:   item.ID,   // 主键id
			Name: item.Name, // 员工姓名
		})
	}
	return result, nil
}
